package com.hu.adapter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hu.common.question.QuestionDto;
import com.hu.pojo.dto.question.QuestionAddRequest;
import com.hu.pojo.dto.question.QuestionUpdateRequest;
import com.hu.pojo.entity.Question;

import java.util.List;

public class QuestionBuilder {

    /**
     * add 请求转为实体类
     * @param request
     * @return
     */
    public static Question builderQuestionAddToQuestion(QuestionAddRequest request){
        Question question = new Question();
        question.setTitle(request.getTitle());
        question.setContent(request.getContent());
        question.setAnswer(request.getAnswer());
        List<String> tags = request.getTags();
        if (CollectionUtil.isNotEmpty(tags)) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        long userId = StpUtil.getLoginIdAsLong();
        question.setCreateBy(userId);
        return question;
    }

    /**
     * update 请求转为实体类
     * @param questionUpdateRequest
     * @return
     */
    public static Question builderQuestionUpdateToQuestion(QuestionUpdateRequest questionUpdateRequest) {
        Question question = new Question();
        question.setId(questionUpdateRequest.getId());
        question.setTitle(questionUpdateRequest.getTitle());
        question.setContent(questionUpdateRequest.getContent());
        question.setAnswer(questionUpdateRequest.getAnswer());
        List<String> tags = questionUpdateRequest.getTags();
        if (CollectionUtil.isNotEmpty(tags)) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        return question;
    }

    public static QuestionDto builderQuestionToQuestionDto(Question question){
        QuestionDto questionDto = new QuestionDto();
        questionDto.setId(question.getId());
        questionDto.setTitle(question.getTitle());
        questionDto.setContent(question.getContent());
        questionDto.setAnswer(question.getAnswer());
        questionDto.setUserId(question.getCreateBy());
        questionDto.setCreateTime(question.getCreateTime());
        questionDto.setUpdateTime(question.getUpdateTime());
        questionDto.setTagList(JSONUtil.toList(question.getTags(), String.class));
        return questionDto;
    }
}
